<?php
namespace app\model;



class winput {
    static function w_input_bangding($system,$config,$fans) {
    global $_P, $_G;
    $recordid = intval($_P['recordid']);
    $sql = "SELECT * FROM " . tablename (t_record) . "
                                WHERE id = :id and (status > 0 or status=-2) ";
    $record = db_find($sql, array(":id"=>$recordid));
    $themeid = $record['themeid'];
    $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
    if(!(!$system['is_multiple_merchants'] || $config['showshop']==0 || ($system['is_multiple_merchants'] && $config['showshop']==$myworker['company']))){
        $myworker = "";
    }

        if (!empty($record['openid'])){
            if($record['openid'] == $_G['openid']){
                $result = array(
                    'msg' => '已绑定成功',
                );
                return $result;
            }else{
                return array('error' =>1 , 'msg' => "此定单已绑定微信:".$record['nickname'] );
            }
        }
        if (empty($myworker)) {
            if ($fans['nickname']=='微信用户'){
                return array('error' =>1 , 'msg' => "请进入活动首页，授权登录后才可绑定");
            }
            $data = array(
                'openid'   => $_G['openid'],
                'uid'      => $_G['member']['uid'],
                'nickname' => $fans['nickname'],
                'avatar'   => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
                'pid'      => $recordid,
                'beizhu' => $record['beizhu'] . date('Y-m-d H:i:s') . ' 绑定微信：' . $fans['nickname'] . '<br>',
            );
            $r = db_update(t_record,$data,array("id"=>$record['id']));



            //绑定后调用微信支付回调
            $sql = "SELECT * FROM " . tablename (t_record) . "
                                WHERE id = :id and (status > 0 or status=-2) ";
            $record = db_find($sql, array(":id"=>$recordid));

            $data = array(
                'username'   => $record['username'],
                'mobile'   => $record['mobile'],
            );
            $r = db_update(t_fans,$data,array("uid"=>$record['uid']));

            $theme = Theme::getThemeById($themeid);
            Common::pay($system,$theme,$config,$record,$recordid,$themeid,$record['fee']);

            if(!empty($r) && $system['iskoi']!=1){
                $result = array(
                    'msg' => '绑定成功',
                );
                return $result;
            }elseif(!empty($r)){
                db_update(t_fans,array('workerid'=>$record['workerid']),array("uid"=>$_G['member']['uid']));
                $config =   Theme::getConfig($themeid);
                $tip_text='';
                if (!empty($config['lz_game_img']) && !empty($config['five_themeid'])){
                    $config2 = Theme::getConfig($config['five_themeid']);
                    Koi::checkInFiveLtTime($config['five_themeid'],$_G['member']['uid'],$config2);
                    $tip_text ='，获得五连抽';
                }

                $result = array(
                    'msg' => $themeid.'five' .$config['five_themeid']. '绑定成功'.$tip_text,
                );
                return $result;
            }else{
                return array('error' =>1 , 'msg' => "保存失败请重试" );
            }
        }else{
            return array('error' =>1 , 'msg' => "只有非员工的微信才可以扫码绑定" );
        }

}
static function w_input($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $recordid = intval($_P['recordid']);
    if ($op=="reset"){
        $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;
        $qrimg = Poster::CreateScene($system,$scene,$config,'Worker/pages/w_input/w_input');

        $data = array(
            'openid'   => "",
            'uid'      => "",
            'nickname' => '未绑定客户微信',
            'avatar'   => $qrimg,
        );
        if (!empty($recordid)){
            db_update(t_record,$data,array("id"=>$recordid));
        }
        $op="getinfo";
    }

    if (!empty($recordid)){
        $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                    WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $recordid));
        $record['shops']=$record['option'];
    }
    //多选处理
    if ($config['shopstype'] == 4 && $config['shops'] && $config['options']) {
//        $options = array_merge($config['gudingoptions'],$config['options']);
        $options=[];
        $selectedFee=0;
        if (empty($record['option']) && !empty($config['gudingoptions'])){
            $record['option'] = implode("|",$config['gudingoptions']);
        }

        if (!empty($config['gudingoptions'])) {
            foreach ($config['gudingoptions'] as $index => $row) {
                $options[]=array(
                    'price'=>$config['shops_price_guding'][$index],
                    'name'=>$row,
                );
            }
        }else{
            $config['gudingoptions'] = array();
        }
        if (!empty($config['options'])) {
            foreach ($config['options'] as $index => $row) {
                $options[]=array(
                    'price'=>$config['shops_price'][$index],
                    'name'=>$row,
                );
            }
        }
        $selectedNumber =0;
        $config['selectedArr']=array();
        $record['option']  = $record['option'] ."|";
        foreach ($options as $index => $row) {
            $config['selectedArr'][$index]['price']=$row['price'];
            $config['selectedArr'][$index]['isguding']=false;
            if(strpos("||".$record['option'], "|".$row['name'] . "|") || in_array($row['name'],$config['gudingoptions'])){
                $config['selectedArr'][$index]['checked']=true;
                $config['selectedArr'][$index]['name']=$row['name'];
                if (in_array($row['name'],$config['gudingoptions'])){
                    $config['selectedArr'][$index]['isguding']=true;
                }
                $selectedFee+=$row['price'];
                $selectedNumber++;
            }else{
                $config['selectedArr'][$index]['checked']=false;
                $config['selectedArr'][$index]['name']=$row['name'];
            }
        }
    }

    if ($op=='display' || $op=="getinfo") {
        if ($_P['renshu']==1){
            $confignew = $config['form2'];
        }elseif ($_P['renshu']==2){
            $confignew = $config['form3'];
        }else{
            $confignew = array(
                'shopstype' => $config['shopstype'],
                'shops' => $config['shops'],
                'options' => $config['options'],
                'addresstype' => $config['addresstype'],
                'address' => $config['address'],
                'addressoptions' => $config['addressoptions'],
                'formtwotype' => $config['formtwotype'],
                'formtwo' => $config['formtwo'],
                'formtwooptions' => $config['formtwooptions'],
                'selectedArr' => $config['selectedArr'],
                'nametext' => $config['nametext'],
                'mobiletext' => $config['mobiletext'],
                'datetimetype' => $config['datetimetype'],
                'datetime' => $config['datetime'],
                'addinfotype' => $config['addinfotype'],
                'addinfo' => $config['addinfo'],
                'shopstype' => $config['shopstype'],
                'shopsmax' => $config['shopsmax'],
                'shopsmin' => $config['shopsmin'],
                'selectedNumber'=>$selectedNumber,
                'selectedFee'=>$selectedFee,
                'selecet_pay'=>$system['selecet_pay'],
                'isedit' => $myworker['level'],
                'is_member_points'=>$system['is_member_points'],
            );
        }
        $confignew['iseditorder'] = $config['iseditorder'];
        $confignew['isedit'] = $myworker['level'];
        $confignew['maxcountall'] = $config['maxcountall'];

        if($config['isxianxia']==1 || $myworker['level'] == 1){
            $confignew['isxianxia'] = true;
        }else{
            $confignew['isxianxia'] = false;
        }

        $feelist = array();
        if ($system['ruanjian']==5){
            if ($system['is_multiple_bargain'] == 1){
                foreach ($config['bargain_products'] as $key =>$item){
                    if (!empty($item['name']) && $item['joinprice'] != '0.00' && !empty($item['joinprice'])){
                        array_push($feelist, array('name'=>$item['name'] .'定金','fee'=>$item['joinprice'],'products_id'=>$key+1));
                    }elseif (!empty($item['name']) && $item['minprice'] != '0.00' && !empty($item['minprice'])){
                        array_push($feelist, array('name'=>$item['name'] .'最低价','fee'=>$item['minprice'],'products_id'=>$key+1));
                    }
                }
            }else{
                if ($config['bargain_joinprice'] != '0.00' && !empty($config['bargain_joinprice'])){
                    array_push($feelist, array('name'=>'定金','fee'=>$config['bargain_joinprice']));
                }elseif ($config['bargain_minprice'] != '0.00' && !empty($config['bargain_minprice'])){
                    array_push($feelist, array('name'=>'最低价','fee'=>$config['bargain_minprice']));
                }
                if ($config['bargain_buy'] != '0.00' && !empty($config['bargain_buy'])){
                    array_push($feelist, array('name'=>$config['bargain_buy_text'],'fee'=>$config['bargain_buy']));
                }
            }

        }else{
            if ($config['joinfee'] != '0.00' && !empty($config['joinfee'])){
                if ($system['jiage']==0) {
                    $payname = '定金';
                }else{
                    $payname = $config['joinname'];
                }
                array_push($feelist, array('name'=>$payname,'fee'=>$config['joinfee']));
            }
            if ($config['joinfee2'] != '0.00' && !empty($config['joinfee2'])){
                array_push($feelist, array('name'=>$config['joinname2'],'fee'=>$config['joinfee2']));
            }
            if ($config['joinfee3'] != '0.00' && !empty($config['joinfee3'])){
                array_push($feelist, array('name'=>$config['joinname3'],'fee'=>$config['joinfee3']));
            }
            if ($config['groupprice'] != '0.00' && !empty($config['groupprice']) && ($_P['renshu']==0 || $system['bottom_jiage'] == '0')){
                array_push($feelist, array('name'=>'拼团价','fee'=>$config['groupprice']));
            }
            if ($config['groupprice2'] != '0.00' && !empty($config['groupprice2']) && $_P['renshu']==1){
                array_push($feelist, array('name'=>'拼团价②','fee'=>$config['groupprice2']));
            }
            if ($config['groupprice3'] != '0.00' && !empty($config['groupprice3']) && $_P['renshu']==2){
                array_push($feelist, array('name'=>'拼团价③','fee'=>$config['groupprice3']));
            }
            if ($config['primeprice'] != '0.00' && !empty($config['primeprice'])){
                array_push($feelist, array('name'=>'单买价','fee'=>$config['primeprice']));
            }
            if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']) {
                array_push($feelist, array('name'=>'全款','fee'=>$config['yukuan']));
                if ($config['joinfee'] != '0.00' && !empty($config['joinfee'])){
                    array_push($feelist, array('name'=>'补差价','fee'=>$config['yukuan'] - $config['joinfee']));
                }elseif ($config['groupprice'] != '0.00' && !empty($config['groupprice'])){
                    array_push($feelist, array('name'=>'补差价','fee'=>$config['yukuan'] - $config['groupprice']));
                }elseif ($config['primeprice'] != '0.00' && !empty($config['primeprice'])){
                    array_push($feelist, array('name'=>'补差价','fee'=>$config['yukuan'] - $config['primeprice']));
                }
            }
        }
        if (empty($feelist)){
//            return array('error' =>1 , 'msg' => "此活动没有配置线上收款" );
            array_push($feelist, array('name'=>'免费报名','fee'=>0));
        }

        foreach ($feelist as $index => $item) {
            $feelist[$index]['fullname']=$item['name'].$item['fee'];
        }

        $confignew = Theme::format_type_config($confignew);
        $result=array();
        $result['op']=$op;
        $result['config']=$confignew;
        $result['feelist'] = $feelist;

        if ($op=="getinfo"){
            if (empty($record['uid']) && strpos($record['avatar'],'yixuansoft.cn')===false){
                $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;
                $qrimg = Poster::CreateScene($system,$scene,$config,'Worker/pages/w_input/w_input');
            }else{
                $qrimg = $record['avatar'];
            }
            $result['qrimg']=$qrimg;
            $result['username']=$record['username'];
            $result['mobile']=$record['mobile'];
        }
        $result['record']=$record;
        $result['level']=$myworker['level'];
        $result['member_from']=array('未标记','老客户','新客户','微信转帐','店内付款');
        return $result;
    }elseif ($op == 'save') {
        $username = $_P['username'];
        $mobile = $_P['mobile'];
        $realfee = $_P['realfee'];
        $payname = $_P['payname'];

        if (empty($username) || empty($mobile)) {
            return array('error' =>1 , 'msg' => "客户姓名与电话不可为空" );
        }

        if (empty($realfee) || $realfee == "0.00"){
            if ($config['joinfee'] != "0.00"){
                $realfee=$config['joinfee'];
            }elseif ($config['groupprice'] != "0.00"){
                $realfee=$config['groupprice'];
            }else{
                $realfee=$config['primeprice'];
            }
        }
        if ($payname == "拼团价②" && $config['groupprice2'] != '0.00' && !empty($config['groupprice2']) && $realfee==$config['groupprice2']){
            $renshu = 1;
        }elseif ($payname == "拼团价③" && $config['groupprice3'] != '0.00' && !empty($config['groupprice3']) && $realfee==$config['groupprice3']){
            $renshu = 2;
        }else{
            $renshu = 0;
        }
        if ($payname == "单买价" && $config['primeprice'] != '0.00' && !empty($config['primeprice']) && $realfee==$config['primeprice']){
            $paytype = 9;
        }else{
            $paytype = 0;
        }
        if ($system['ruanjian']==5){
            $paytype = 20;
        }

        $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
        $data = array(
            'uniacid'  => $_G['mpid'],
            'themeid'  => $themeid,
            'openid'   => '',
            'uid'      => '',
            'nickname' => '',
            'avatar'   => '',
            'username' => $username,
            'mobile'   => $mobile,
            'addtime'  => TIMESTAMP,
            'fee'      => $realfee,
            'option' => $_P['option']=='undefined'?'':trim($_P['option']),
            'address' => $_P['address']=='undefined'?'':trim($_P['address']),
            'formtwo' => $_P['formtwo']=='undefined'?'':trim($_P['formtwo']),
            'datetime' => $_P['datetime']=='undefined'?'':trim($_P['datetime']),
            'addinfo' => $_P['addinfo']=='undefined'?'':trim($_P['addinfo']),
            'member_beizhu' => $_P['member_beizhu']=='undefined'?$record['member_beizhu']:$_P['member_beizhu'],
            'code'     => '',
            'uncode'   => $uncode,
            'status'   => 3,
            'fromuid'  => $_G['member']['uid'],
            'fopenid'  => $_G['openid'],
            'workerid'  => $_G['member']['uid'],
            'pid'      => 0,
            'type'     => $paytype,
            'tuannum' =>1,
            'renshu'     => $renshu,
            'chongzhi' => $_P['chongzhi']=='undefined'?0:floatval($_P['chongzhi']),
            'member_beizhu' => $_P['member_beizhu']=='undefined'?'':$_P['member_beizhu'],
            'is_member' => $_P['is_member']=='undefined'?0:intval($_P['is_member']),
        );
        if ($system['is_multiple_bargain'] == 1){
            $data['products_id']=intval($_P['products_id']);
        }

        $data['username']=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$data['username']);
        $data['mobile']=preg_replace('#[^0-9]#u','',$data['mobile']);
        $data['option']=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_.,|，\-]#u','',$data['option']);
        $data['address']=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$data['address']);
        $data['formtwo']=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$data['formtwo']);
        $data['datetime']=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$data['datetime']);
        $data['addinfo']=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$data['addinfo']);
        $data['address'] = str_replace('请选择','',$data['address']);
        $data['formtwo'] = str_replace('请选择','',$data['formtwo']);
        $data['option'] = str_replace('请选择','',$data['option']);

        $addtime = TIMESTAMP-120;
            $sql = "SELECT * FROM " . tablename (t_record) . "
                                        WHERE themeid =:themeid and username = :username
                                                and mobile = :mobile and type = 0 and status=3 and addtime >" . $addtime . " ";
            $row = db_find($sql, array(":themeid"=>$themeid,":username"=>$username,":mobile"=>$mobile));

        if (!empty($row)) {
            return array('error' =>1 , 'msg' =>"客户“".$username."”在2分钟内录入过线下定单，若实际为多个定单请在2分钟以后再次录入" );
        } else {
            Theme::workerreport($themeid,$_G['member']['uid'],array('recordxx' =>1));
            $r = $insertid = db_insert(t_record,$data);
        }

        if(!empty($r)){
            $recordid = $insertid;
            $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;

            $qrimg = Poster::CreateScene($system,$scene,$config,'Worker/pages/w_input/w_input');
            // echo $qrimg;
            $data = array(
                'nickname' => '未绑定客户微信',
                'avatar'   => $qrimg,
            );
            $r = db_update(t_record,$data,array("id"=>$recordid));
        }
        $result = array(
            'qrimg' => $qrimg,
            'username' => $username,
            'mobile'   => $mobile,
        );
        $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $recordid));
        $result['record']=$record;
        return $result;
    }
}
}